package com.itheima.prize.api.action;

import com.alibaba.fastjson.JSON;
import com.itheima.prize.api.config.LuaScript;
import com.itheima.prize.commons.config.RedisKeys;
import com.itheima.prize.commons.db.entity.*;
import com.itheima.prize.commons.utils.ApiResult;
import com.itheima.prize.commons.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/act")
@Api(tags = {"抽奖模块"})
public class ActController {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private LuaScript luaScript;

    @GetMapping("/limits/{gameid}")
    @ApiOperation(value = "剩余次数")
    @ApiImplicitParams({
            @ApiImplicitParam(name="gameid",value = "活动id",example = "1",required = true)
    })
    public ApiResult<Object> limits(@PathVariable int gameid, HttpServletRequest request){
        //获取活动基本信息
        CardGame game = (CardGame) redisUtil.get(RedisKeys.INFO+gameid);
        if (game == null){
            return new ApiResult<>(-1,"活动未加载",null);
        }
        //获取当前用户
        HttpSession session = request.getSession();
        CardUser user = (CardUser) session.getAttribute("user");
        if (user == null){
            return new ApiResult(-1,"未登陆",null);
        }
        //用户可抽奖次数
        Integer enter = (Integer) redisUtil.get(RedisKeys.USERENTER+gameid+"_"+user.getId());
        if (enter == null){
            enter = 0;
        }
        //根据会员等级，获取本活动允许的最大抽奖次数
        Integer maxenter = (Integer) redisUtil.hget(RedisKeys.MAXENTER+gameid,user.getLevel()+"");
        //如果没设置，默认为0，即：不限制次数
        maxenter = maxenter==null ? 0 : maxenter;

        //用户已中奖次数
        Integer count = (Integer) redisUtil.get(RedisKeys.USERHIT+gameid+"_"+user.getId());
        if (count == null){
            count = 0;
        }
        //根据会员等级，获取本活动允许的最大中奖数
        Integer maxcount = (Integer) redisUtil.hget(RedisKeys.MAXGOAL+gameid,user.getLevel()+"");
        //如果没设置，默认为0，即：不限制次数
        maxcount = maxcount==null ? 0 : maxcount;

        //幸运转盘类，先给用户随机剔除，再获取令牌，有就中，没有就说明抢光了
        //一般这种情况会设置足够的商品，卡在随机上
        Integer randomRate = (Integer) redisUtil.hget(RedisKeys.RANDOMRATE+gameid,user.getLevel()+"");
        if (randomRate == null){
            randomRate = 100;
        }

        Map map = new HashMap();
        map.put("maxenter",maxenter);
        map.put("enter",enter);
        map.put("maxcount",maxcount);
        map.put("count",count);
        map.put("randomRate",randomRate);

        return new ApiResult<>(1,"成功",map);
    }
    @GetMapping("/go/{gameid}")
    @ApiOperation(value = "抽奖")
    @ApiImplicitParams({
            @ApiImplicitParam(name="gameid",value = "活动id",example = "1",required = true)
    })
    public ApiResult<Object> act(@PathVariable int gameid, HttpServletRequest request){
        //获取用户信息
        CardUser user = (CardUser)request.getSession().getAttribute("user");
        if(user==null){
            return new ApiResult<>(-1,"未登入",null);
        }
        //获取当前时间
        Date time = new Date();
        long now = time.getTime();
        //获取用户id
        Integer userId = user.getId();
        //获取用户等级
        Integer userLevel = user.getLevel();
        //创建用户游戏对象并设置相关属性
        CardUserGame cardUserGame = new CardUserGame(userId,gameid,time);
        //调用lua脚本开始抽奖
        Long result = luaScript.tokenCheck(gameid, userId, userLevel,now);
        //判断抽奖结果
        switch (result.intValue()){
            case -2:
                return new ApiResult<>(-1,"活动未开始",null);
            case -1:
                return new ApiResult<>(-1,"活动已结束",null);
            case 0:
                return new ApiResult<>(-1,"您的抽奖次数已用完",null);
            case 1:
                //rabbitMQ异步消息处理，记录用户参与游戏
                if(redisUtil.setNx(RedisKeys.USERGAME + gameid+"_"+userId, 1)){
                    rabbitTemplate.convertAndSend("prize_exchange_direct","prize_queue_play", JSON.toJSONString(cardUserGame));
                }
                return new ApiResult<>(-1,"未中奖",null);
            default:
                //根据令牌获取对应的奖励
                CardProductDto Product = (CardProductDto)redisUtil.hget(RedisKeys.TOKENS + gameid, result.toString());

                //创建用户中奖对象并设置相关属性
                CardUserHit cardUserHit = new CardUserHit(gameid,userId, Product.getId(), time);

                //rabbitMQ异步消息处理，记录用户参与游戏
                if(redisUtil.setNx(RedisKeys.USERGAME + gameid+"_"+userId, 1)){
                    rabbitTemplate.convertAndSend("prize_exchange_direct","prize_queue_play", JSON.toJSONString(cardUserGame));
                }

                //rabbitMQ异步消息处理，记录用户中奖
                rabbitTemplate.convertAndSend("prize_exchange_direct","prize_queue_hit",JSON.toJSONString(cardUserHit));
                //返回中奖信息
                return new ApiResult<>(1,"恭喜中奖",Product);
        }
    }
}
